package cn.yunyichina.provider.framework.annotation.validate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Collection;

/**
 * Validate the @ValidateNotNull annotation
 *
 * @author jiangtch
 */
public class ValidateNotNullAndNotEmptyHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateNotNullHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidateNotNullAndNotEmpty.class)) {
            checkNotNullAndNotEmpty(validatedObj, field);
        }
    }

    private void checkNotNullAndNotEmpty(AnnotationValidable filter, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkNotNullAndNotEmpty()");
        }
        Object dest;
        try {
            dest = GetFiledValue.getField(filter, field.getName());
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        if (dest == null) {
            logger.warn("字段：" + field.getName() + "为空值，请检查!");
            throw new ValidateException("字段：" + field.getName() + "为空值，请检查!");
        }
        if (dest instanceof String) {
            if (((String) dest).length() == 0) {
                logger.warn("字段：" + field.getName() + "为空字符串，请检查!");
                throw new ValidateException("字段：" + field.getName() + "为空字符串，请检查!");
            }
        } else if (dest instanceof Collection) {
            if (((Collection) dest).size() == 0) {
                logger.warn("字段：" + field.getName() + "为空集合，请检查!");
                throw new ValidateException("字段：" + field.getName() + "为空集合，请检查!");
            }
        }
    }

}
